const { CampusAccount } = require('../models');
const { AppError } = require('../middlewares/errorHandler');
const { Op } = require('sequelize');
const { SystemLog } = require('../models');

class CampusAccountController {
  /**
   * 获取校园账户列表
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async getCampusAccounts(ctx) {
    const { page = 1, limit = 10, account_type, status } = ctx.query;
    const offset = (page - 1) * limit;

    const where = {};
    if (account_type) where.account_type = account_type;
    if (status) where.status = status;

    const { count, rows: accounts } = await CampusAccount.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    ctx.body = {
      status: 'success',
      data: {
        total: count,
        accounts
      }
    };
  }

  /**
   * 获取单个校园账户
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async getCampusAccount(ctx) {
    const { id } = ctx.params;
    const account = await CampusAccount.findByPk(id);

    if (!account) {
      throw new AppError(404, '校园账户不存在');
    }

    ctx.body = {
      status: 'success',
      data: {
        account
      }
    };
  }

  /**
   * 创建校园账户
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async createCampusAccount(ctx) {
    const accountData = ctx.request.body;

    // 检查员工号是否已存在
    if (accountData.employee_id) {
      const existingAccount = await CampusAccount.findOne({
        where: { employee_id: accountData.employee_id }
      });

      if (existingAccount) {
        throw new AppError(400, '员工号已存在');
      }
    }

    const account = await CampusAccount.create(accountData);

    ctx.status = 201;
    ctx.body = {
      status: 'success',
      data: {
        account
      }
    };
  }

  /**
   * 更新校园账户
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async updateCampusAccount(ctx) {
    const { id } = ctx.params;
    const updateData = ctx.request.body;

    const account = await CampusAccount.findByPk(id);
    if (!account) {
      throw new AppError(404, '校园账户不存在');
    }

    // 检查员工号是否已被其他账户使用
    if (updateData.employee_id && updateData.employee_id !== account.employee_id) {
      const existingAccount = await CampusAccount.findOne({
        where: { employee_id: updateData.employee_id }
      });

      if (existingAccount) {
        throw new AppError(400, '员工号已被使用');
      }
    }

    await account.update(updateData);

    ctx.body = {
      status: 'success',
      data: {
        account
      }
    };
  }

  /**
   * 删除校园账户
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async deleteCampusAccount(ctx) {
    const { id } = ctx.params;
    const account = await CampusAccount.findByPk(id);

    if (!account) {
      throw new AppError(404, '校园账户不存在');
    }

    await account.destroy();

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  /**
   * 搜索校园账户
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async searchCampusAccounts(ctx) {
    const { keyword, account_type, status } = ctx.query;
    const where = {};

    if (keyword) {
      where[Op.or] = [
        { student_id: { [Op.like]: `%${keyword}%` } },
        { name: { [Op.like]: `%${keyword}%` } },
        { email: { [Op.like]: `%${keyword}%` } },
        { phone: { [Op.like]: `%${keyword}%` } }
      ];
    }

    if (account_type) where.account_type = account_type;
    if (status) where.status = status;

    const accounts = await CampusAccount.findAll({
      where,
      order: [['created_at', 'DESC']],
      limit: 20
    });

    ctx.body = {
      status: 'success',
      data: {
        accounts
      }
    };
  }

  /**
   * 更新校园账户状态
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async updateStatus(ctx) {
    const { id } = ctx.params;
    const { status } = ctx.request.body;
    const userId = ctx.state.user.id;

    const account = await CampusAccount.findByPk(id);
    if (!account) {
      throw new AppError(404, '校园账户不存在');
    }

    // 验证状态值
    const validStatuses = ['active', 'inactive', 'graduated', 'suspended'];
    if (!validStatuses.includes(status)) {
      throw new AppError(400, '无效的状态值');
    }

    await account.update({ 
      status,
      statusUpdatedAt: new Date(),
      statusUpdatedBy: userId
    });

    // 记录操作日志
    await SystemLog.create({
      action: 'update_campus_account_status',
      operator: userId,
      target_type: 'campus_account',
      target_id: id,
      details: { 
        before: account.status,
        after: status
      }
    });

    ctx.body = {
      status: 'success',
      data: {
        account
      }
    };
  }

  /**
   * 更新学术状态
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async updateAcademicStatus(ctx) {
    const { id } = ctx.params;
    const { academicStatus } = ctx.request.body;
    const userId = ctx.state.user.id;

    const account = await CampusAccount.findByPk(id);
    if (!account) {
      throw new AppError(404, '校园账户不存在');
    }

    // 验证学术状态值
    const validAcademicStatuses = ['normal', 'probation', 'suspended'];
    if (!validAcademicStatuses.includes(academicStatus)) {
      throw new AppError(400, '无效的学术状态值');
    }

    await account.update({ 
      academicStatus,
      academicStatusUpdatedAt: new Date(),
      academicStatusUpdatedBy: userId
    });

    // 记录操作日志
    await SystemLog.create({
      action: 'update_academic_status',
      operator: userId,
      target_type: 'campus_account',
      target_id: id,
      details: { 
        before: account.academicStatus,
        after: academicStatus
      }
    });

    ctx.body = {
      status: 'success',
      data: {
        account
      }
    };
  }
}

module.exports = new CampusAccountController(); 